package pacs_server

import (
	"fmt"
	"gitee.com/uni-minds/bridge-pacs/global"
	"time"
)

func (dm *PacsManager) Sync(chkMedia bool, syncStep int, quickMode bool) (stat ImportDetails) {
	global.FlagSetChkMedia(chkMedia)

	stat = ImportDetails{
		CountStudies:  0,
		CountSeries:   0,
		CountInstance: 0,
		ImportStudies: make([]string, 0),
	}

	for _, servername := range dm.GetServerNameAll() {
		si, err := dm.GetServer(servername)
		if err != nil {
			panic(err.Error())
		}

		switch si.ServerType {
		case "pacs", "dcm4chee":
			tmpStat := si.ProcessPacsDcm4cheeServer(syncStep, 5, quickMode)
			stat.CountStudies += tmpStat.CountStudies
			stat.CountSeries += tmpStat.CountSeries
			stat.CountInstance += tmpStat.CountInstance
			stat.ImportStudies = append(stat.ImportStudies, tmpStat.ImportStudies...)

			dm.Log(si.ServerHost, "import result\n", stat.ImportStudies)
		default:
			fmt.Println("unknown server type:", si.ServerType)
		}
	}
	return stat
}

func (dm *PacsManager) AutoSync(sec int) {
	dm.Log(fmt.Sprintf("AutoSync %d sec", sec))

	dm.autoSyncStopSign = make(chan int, 0)
	dm.autoSyncDuration = time.Duration(sec) * time.Second

	go func() {
		for {
			select {
			case <-dm.autoSyncStopSign:
				dm.Log("stop sign")
				return

			case <-time.Tick(dm.autoSyncDuration):
				dm.Log("tick")
				dm.Sync(false, 2, true)

			}
		}
	}()
}

func (dm *PacsManager) AutoSyncOff() {
	fmt.Println("try stop auto sync")
	dm.autoSyncStopSign <- 1
	fmt.Println("sent sync stop sign")
}
